package com.zscat.mallplus.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.sys.domain.TreeSelect;
import com.zscat.mallplus.sys.entity.*;
import com.zscat.mallplus.sys.service.*;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/sys/sysDept")
public class SysDeptController extends ApiController {

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysUserService sysUserService;

    @GetMapping(value = "/list")
    public Object getUserByPage(SysDept entity,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize) {
        try {
            return new CommonResult().success(this.buildDeptTreeList(sysDeptService.page(new Page<>(pageNum, pageSize), new QueryWrapper<>(entity)).getRecords()));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTreeList(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 新增部门
     *
     * @param entity
     * @return
     */
    @PostMapping(value = "/add")
    public Object saveDept(@RequestBody SysDept entity) {
        try {
            SysDept info = sysDeptService.getOne(new QueryWrapper<SysDept>().eq("dept_name", entity.getDeptName()));
            if (info != null) {
                return new CommonResult().failed("新增部门'" + entity.getDeptName() + "'失败，部门名称已存在");
            }
            if (sysDeptService.save(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    /**
     * 修改部门
     *
     * @param entity
     * @return
     */
    @PostMapping(value = "/update")
    public Object updateUser(@RequestBody SysDept entity) {
        try {
//            SysDept info = sysDeptService.getOne(new QueryWrapper<SysDept>().eq("dept_name", entity.getDeptName()));
//            if (info != null) {
////                return new CommonResult().failed("修改部门'" + entity.getDeptName() + "'失败，部门名称已存在");
//            } else
            if (entity.getParentId().equals(entity.getDeptId())) {
                return new CommonResult().failed("修改部门'" + entity.getDeptName() + "'失败，上级部门不能是自己");
            }
            if (sysDeptService.updateById(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    /**
     * 删除部门
     */
    @GetMapping(value = "/delete/{deptId}")
    public Object deleteUser(@PathVariable Long deptId) {
        try {
            if (ValidatorUtils.empty(deptId)) {
                return new CommonResult().paramFailed("id不能为空！");
            }
            //
            List<SysDept> sysDeptList = sysDeptService.list(new QueryWrapper<SysDept>().eq("parent_id", deptId));
            if (sysDeptList.size() > 0) {
                return new CommonResult().failed("存在下级部门,不允许删除");
            }
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("dept_id", deptId));
            if (sysUser != null) {
                return new CommonResult().failed("部门存在用户,不允许删除");
            }
            SysDept sysDept = sysDeptService.getById(deptId);
            if (sysDeptService.removeById(sysDept)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public Object getUserById(@PathVariable Long deptId) {
        try {
            if (ValidatorUtils.empty(deptId)) {
                return new CommonResult().paramFailed("用户id");
            }
            SysDept sysDept = sysDeptService.getById(deptId);
            return new CommonResult().success(sysDept);
        } catch (Exception e) {
            return new CommonResult().failed();
        }
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public Object treeselect(SysDept dept) {
        List<SysDept> depts = sysDeptService.list(null);
        List<SysDept> deptTrees = buildDeptTree(depts);
        return new CommonResult().success(deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList()));
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext()) {
                    SysDept n = (SysDept) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (!ValidatorUtils.empty(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


}

